package com.ssm.service;

import com.alibaba.fastjson.JSON;
import com.hqj.ReturnUtil;
import com.ssm.dao.MenuDao;
import com.ssm.dao.RoleDao;
import com.ssm.entity.Menu;
import com.ssm.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class RoleServiceI implements BaseService<Role> {

    @Autowired
    private RoleDao rd;
    @Autowired
    private MenuDao md;

    @Override
    public Role get(Role role) {
        List<Role> list = rd.find(role);
        return list.size()>0?list.get(0):new Role();
    }

    public Map<String,Object> grant(String mids,int rid){
        int j = rd.removeRoleMenu(rid);
        //把字符串的菜单id转换为集合
        List<String> ids = JSON.parseArray(mids,String.class);
        Set<Integer> set = new HashSet<Integer>();
        for(String pid:ids) {
            getMenuIds(Integer.parseInt(pid),md.find(new Menu()),set);
        }
        if(ids.size()>0){
            int i = rd.grant(set,rid);
            return ReturnUtil.returnMap(i>0,"授权");
        }else{
            return ReturnUtil.returnMap(true,"授权");
        }
    }


    public Set<Integer> getMenuIds(int pid,List<Menu> list,Set<Integer> ids){

        for(Menu m:list){
            if(pid==0){
                break;
            }
            if(pid == m.getId()){
                ids.add(m.getId());
                getMenuIds(m.getParentId(),list,ids);
            }
        }
        return ids;
    }

    public List<Integer> findRoleMenu(int rid){
        List<Integer> list = rd.findRoleMenu(rid);
        return list;
    }

    @Override
    public List<Role> find(Role role) {
        return rd.find(role);
    }

    @Override
    public Map<String, Object> add(Role role) {

        return null;
    }

    @Override
    public Map<String, Object> edit(Role role) {
        return null;
    }

    @Override
    public Map<String, Object> remove(Role role) {
        return null;
    }
}
